package com.example.mq;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.example.api.config.OtherConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
 * 消息发送
 *
 * @author lr
 * @create 2021/9/17
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AmqpSend {

    private final RabbitTemplate rabbitTemplate;


    private final OtherConfig otherConfig;


    /**
     * @param
     */
    @Async
    public void sendMqMessages(String json) {
        if (StrUtil.isBlank(json)) {
            log.info("消息体为空，消费失败");
           throw  new NullPointerException("消息发送为空");
        }
        final String messageId = UUID.randomUUID().toString();

        try {
            rabbitTemplate.convertAndSend(otherConfig.getExchange(), otherConfig.getProjectMessage(), json, message -> {
                 message.getMessageProperties().setHeader("message_id",messageId);
                 return message;
            },new CorrelationData(messageId));
        } catch (AmqpException e) {
            log.error("消息发送失败，targetId：{},失败原因{}", messageId, e.getMessage());
        }
    }


}